package top.lishuoboy.javaweb.a16json_ajax;

import cn.hutool.core.map.MapUtil;
import top.lishuoboy.dependency.base.json.HuJsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * ajax后台
 *
 * @author lishuoboy
 * @date 2022-01-13 23:09
 */
@WebServlet(name = "AjaxServlet", value = "/AjaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        Map map = MapUtil.<String, Object>builder()
            .put("id", 111)
            .put("msg", "hello " + name + ", 我收到 get 请求").build();

        String jsonStr = HuJsonUtil.toJsonStr(map);
        System.out.println(jsonStr);
        resp.getWriter().write(jsonStr);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        Map map = MapUtil.<String, Object>builder()
            .put("id", 111)
            .put("msg", "hello " + name + ", 我收到 post 请求").build();

        String jsonStr = HuJsonUtil.toJsonStr(map);
        System.out.println(jsonStr);
        resp.getWriter().write(jsonStr);
    }
}
